package lib.pacificapp.widget;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshWebView; 
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
 
 
import android.content.Context; 
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.AttributeSet;  
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView; 
import android.webkit.WebViewClient;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings.ZoomDensity;
import android.widget.LinearLayout; 

public class IFrame extends  LinearLayout {
    public interface OnLoadListener{
    	    void onCompleted(int code,String str); 
    	    void onStartd();
    }
    private OnLoadListener mOnLoadListener;
    public void setOnLoadListener(OnLoadListener lis){
    	mOnLoadListener=lis;
    }
    public void setHTML(String html){
   	 if(webview!=null)
   		 webview.loadData(fmtString(html), "text/html", "utf-8");
   }
    public void setHTML(String html,String code,String code2){
      	 if(webview!=null)
      		 webview.loadData(fmtString(html,code), "text/html",code2);
      }
    public void setPNG(String html){
    	 
      	 if(webview!=null)
      		 webview.loadData(html,"image/png", "utf-8");
      }
    
    private String username;
    private String password;
    public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setSrc(String url){
    	  if(this.getUsername()!=null&&this.getPassword()!=null){
        	
    	    	  Map<String,String> header = new HashMap<String, String>();
    	       	  String data1=Base64.encodeToString((getUsername()+":"+getPassword()).getBytes(), Base64.DEFAULT);
    	       	  header.put("Authorization", "Basic "+data1);
    	       	   getWebview().loadUrl(url, header);
    	 }else
    	this.getWebview().loadUrl(url);
    }
    private String fmtString(String str){
    	String notice = "";
    	try{
    	notice = URLEncoder.encode(str, "utf-8");
    	}catch(UnsupportedEncodingException ex){
    	}
    	return notice;
    	}
    private String fmtString(String str,String code){
    	String notice = "";
    	try{
    	notice = URLEncoder.encode(str, "utf-8");
    	}catch(UnsupportedEncodingException ex){
    	}
    	return notice;
    	} 
    public void completed(){
    	   if(pulltorefresh!=null)
    		 pulltorefresh.onRefreshComplete();
    }
     
    
    public IFrame(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		 initView();
	}

	public IFrame(Context context, AttributeSet attrs) {
		super(context, attrs);
		 initView();
//		try{
//			initView();
//			}finally{}
		// TODO Auto-generated constructor stub
	}
   
	/***刷新控件*/
	private PullToRefreshWebView pulltorefresh;
	
	private WebView webview;
	private void initView(){
        
		pulltorefresh=new PullToRefreshWebView(getContext()); 
		LinearLayout.LayoutParams ps=new LinearLayout.LayoutParams(-1, -1);
		 addView(pulltorefresh,ps);
		pulltorefresh.getLoadingLayoutProxy().setLastUpdatedLabel("最后更新在1小时前");   
		pulltorefresh.getLoadingLayoutProxy().setPullLabel("下拉刷新");  
		pulltorefresh.getLoadingLayoutProxy().setRefreshingLabel("正在刷新");  
		pulltorefresh.getLoadingLayoutProxy().setReleaseLabel("松开刷新");  
//        
	 
		 
		pulltorefresh.setOnRefreshListener(new OnRefreshListener<WebView>(){
			@Override  
			public void onRefresh(PullToRefreshBase<WebView> arg0) {
				// TODO Auto-generated method stub
				 getWebview().reload();
			    //mFocusPanel.onRefreshComplete(); 
			    
			}});
//          
  
     
		  setWebview(pulltorefresh.getRefreshableView()); 
		  setModeH5();
		 
	}
	
    public void setModeH5(){
    	 getWebview().setWebViewClient(new WebViewClient(){
	    	@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
			     super.onPageFinished(view, url);
			      if(mOnLoadListener!=null)
	            		mOnLoadListener.onCompleted(200,"");
	            	else  pulltorefresh.onRefreshComplete();
			}
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
            	// TODO Auto-generated method stub
            	super.onPageStarted(view, url, favicon);
            	
            	if(mOnLoadListener!=null)
            		mOnLoadListener.onStartd();
            }
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				// TODO Auto-generated method stub
				super.onReceivedError(view, errorCode, description, failingUrl);
				if(mOnLoadListener!=null)
            		mOnLoadListener.onCompleted(errorCode,description);
			}
			  @Override  
	          public boolean shouldOverrideUrlLoading(WebView view, String url)  
	             {  
	                 view.loadUrl(url);  
	                 return true;  
	             }  
	    });
    	 
    	 
		WebSettings webSettings = webview.getSettings();  
		webSettings.setJavaScriptEnabled(true);  
       //User settings           
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);  
		webSettings.setUseWideViewPort(true);//关键点  

		webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);  
		     
		webSettings.setAllowFileAccess(true); // 允许访问文件  
		webSettings.setBuiltInZoomControls(true); // 设置显示缩放按钮  
		webSettings.setSupportZoom(true); // 支持缩放  

	 

		webSettings.setLoadWithOverviewMode(true);  

		DisplayMetrics metrics = new DisplayMetrics();  
		WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
		 wm.getDefaultDisplay().getMetrics(metrics);   
		int mDensity = metrics.densityDpi;   
		if (mDensity == 240) {   
		webSettings.setDefaultZoom(ZoomDensity.FAR);  
		} else if (mDensity == 160) {  
		webSettings.setDefaultZoom(ZoomDensity.MEDIUM);  
		} else if(mDensity == 120) {  
		webSettings.setDefaultZoom(ZoomDensity.CLOSE);  
		}else if(mDensity == DisplayMetrics.DENSITY_XHIGH){  
		webSettings.setDefaultZoom(ZoomDensity.FAR);   
		}else if (mDensity == DisplayMetrics.DENSITY_TV){  
		webSettings.setDefaultZoom(ZoomDensity.FAR);   
		}else{  
		 webSettings.setDefaultZoom(ZoomDensity.MEDIUM);  
		}  
        /**  
		* 用WebView显示图片，可使用这个参数 设置网页布局类型： 1、LayoutAlgorithm.NARROW_COLUMNS ：  
		* 适应内容大小 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放  
		*/  
     	webSettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);  
				 
	 	 
    }
	public WebView getWebview() {
		return webview;
	}
	public void setWebview(WebView webview) {
		this.webview = webview;
	}
	

}
